package com.hko.qrip.service.impl;

import it.sauronsoftware.ftp4j.FTPFile;

import java.io.File;
import java.io.FilenameFilter;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.springframework.beans.factory.annotation.Autowired;

import com.hko.qrip.bean.GlygaAAlert;
import com.hko.qrip.dao.FtpLogDao;
import com.hko.qrip.dao.GlygaDao;
import com.hko.qrip.manager.FTPManager;
import com.hko.qrip.service.GlygaService;
import com.hko.qrip.util.QripJobOptions;

public class GlygaServiceImpl implements GlygaService {

	private static String ALERT_LINE = "K";
	@Autowired
	private QripJobOptions jobOptions;

	@Autowired
	private GlygaDao glygaDao;

	@Autowired
	private FtpLogDao ftpLogDao;

	@Override
	public int insertAAlert(GlygaAAlert alert) throws SQLException {
		return glygaDao.insertAAlert(alert);
	}

	@Override
	public void doSync() throws Exception {
		System.out.println("[INFO] Glyga sync service started");
		File[] files = downloadFiles();
		for (File file : files) {
			List<GlygaAAlert> alerts = getAlertFile(file);
			int insertCount = 0;
			for (GlygaAAlert alert : alerts) {
				insertCount += insertAAlert(alert);
			}
			System.out.println(insertCount + " alerts inserted");
			ftpLogDao.insertTableLog(file.getName(), insertCount, alerts.size(), "");
			file.delete();
		}
		System.out.println("[INFO] Glyga sync service ended");

	}

	private File[] downloadFiles() throws Exception {
		FTPManager fm = new FTPManager(jobOptions.getFtpHost(), jobOptions.getFtpUser(), jobOptions.getFtpPassword());
		fm.ftpLogin();
		fm.changeDir(jobOptions.getFtpPath());
		FTPFile[] files = fm.listFiles("glyga*");
		for (FTPFile file : files) {
			fm.downloadAndDeleteFile(jobOptions.getLocalFilePath() + file.getName(), file.getName());
			System.out.println("downloaded: " + file.getName());
			ftpLogDao.insertFtpLog(file.getName());
		}
		fm.close();

		File lrDir = new File(jobOptions.getLocalFilePath());
		File[] lrFiles = lrDir.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File arg0, String arg1) {
				if (arg1.contains("glyga")) {
					return true;
				}
				return false;
			}
		});

		return lrFiles;

	}

	private List<GlygaAAlert> getAlertFile(File file) throws Exception {
		List<GlygaAAlert> resultList = new ArrayList<GlygaAAlert>();

		Scanner fin = new Scanner(file);
		while (fin.hasNextLine()) {
			String line = fin.nextLine().trim();
			if (!line.contains(ALERT_LINE) || line.split(" ").length < 6) {
				continue;
			}
			GlygaAAlert alert = new GlygaAAlert();
			alert.setDatetime(new Timestamp((Long.parseLong(line.split(" ")[0]) - 8 * 60 * 60) * 1000L));
			alert.setCorridor(line.split(" ")[2]);
			alert.setMagnitude(Integer.parseInt(line.split(" ")[3].replace("K", "").replace("+", "")));
			alert.setLocation(line.split(" ")[4]);
			alert.setAlertType(line.split(" ")[5]);
			resultList.add(alert);
		}
		fin.close();

		return resultList;
	}
}
